<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" :footer="null">
    <div class="step-form-container">
      <!-- 步骤条 -->
      <a-steps :current="currentStep" class="step-steps">
        <a-step title="基本信息" description="填写脚本名称、描述等基本信息" />
        <a-step title="脚本内容" description="编写脚本代码和功能特性" />
        <a-step title="高级设置" description="设置图标、颜色、状态等" />
      </a-steps>

      <!-- 第一步：基本信息 -->
      <div v-show="currentStep === 0" class="step-content">
        <a-form :model="formData" layout="vertical">
          <a-form-item label="脚本名称" required>
            <a-input v-model:value="formData.name" placeholder="请输入脚本名称" />
          </a-form-item>
          <a-form-item label="文件名" required>
            <a-input v-model:value="formData.fileName" placeholder="请输入文件名，如：script.sh" />
            <div class="form-tip">提示：文件名应包含扩展名，如 .sh、.py、.js 等</div>
          </a-form-item>
          <a-form-item label="脚本描述" required>
            <a-textarea v-model:value="formData.description" placeholder="请输入脚本描述，说明脚本的功能和用途" :rows="4" />
            <div class="form-tip">提示：详细描述脚本的功能、使用场景和注意事项</div>
          </a-form-item>
          <a-form-item label="文件大小(字节)">
            <a-input-number v-model:value="formData.fileSize" placeholder="请输入文件大小" style="width: 100%" />
          </a-form-item>
        </a-form>
      </div>

      <!-- 第二步：脚本内容 -->
      <div v-show="currentStep === 1" class="step-content">
        <a-form :model="formData" layout="vertical">
          <a-form-item label="脚本代码内容" required>
            <Suspense>
              <template #default>
                <CodeEditor v-model:value="formData.content" mode="javascript" style="height: 400px" />
              </template>
              <template #fallback>
                <a-skeleton active :paragraph="{ rows: 20 }" style="height: 400px" />
              </template>
            </Suspense>
          </a-form-item>
          <a-row :gutter="12">
            <a-col :span="12">
              <a-form-item label="支持系统">
                <a-input v-model:value="systemsInput" placeholder="请输入支持的系统，如：Linux,Windows,macOS" />
                <div class="form-tip">提示：多个系统用逗号分隔</div>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="技术栈">
                <a-input v-model:value="techStackInput" placeholder="请输入技术栈，如：Shell,Python,Node.js" />
                <div class="form-tip">提示：多个技术栈用逗号分隔</div>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="功能特性">
            <a-textarea v-model:value="featuresInput" placeholder="请输入功能特性，如：自动化部署,日志分析,性能监控" :rows="3" />
            <div class="form-tip">提示：多个功能特性用逗号分隔，详细描述脚本的主要功能</div>
          </a-form-item>
        </a-form>
      </div>

      <!-- 第三步：高级设置 -->
      <div v-show="currentStep === 2" class="step-content">
        <a-form :model="formData" layout="vertical">
          <a-row :gutter="12">
            <a-col :span="12">
              <a-form-item label="脚本图标">
                <div class="emoji-form-row">
                  <a-input v-model:value="icon" placeholder="点击右侧图标选择" readonly class="emoji-input" />
                  <template v-if="icon">
                    <a-button type="text" size="small" @click="icon = ''" class="clear-emoji">清除</a-button>
                  </template>
                  <template v-else>
                    <Vue3Emoji size="small" :options-name="optionsName" @click-emoji="selectEmoji" />
                  </template>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="脚本状态" required>
                <a-radio-group v-model:value="formData.status">
                  <a-radio value="active">启用</a-radio>
                  <a-radio value="inactive">禁用</a-radio>
                  <a-radio value="draft">草稿</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="脚本颜色">
            <div class="color-selector">
              <div class="color-presets">
                <div
                  v-for="color in colorPresets"
                  :key="color"
                  class="color-option"
                  :style="{ background: color }"
                  :class="{ active: formData.color === color }"
                  @click="formData.color = color"
                ></div>
              </div>
              <div v-if="formData.color" class="selected-color" :style="{ background: formData.color }">
                <span class="color-value">{{ formData.color }}</span>
                <a-button type="text" size="small" @click="formData.color = ''" class="clear-color"> 清除 </a-button>
              </div>
            </div>
          </a-form-item>
          <a-row :gutter="12">
            <a-col :span="8">
              <a-form-item label="下载次数">
                <a-input-number v-model:value="formData.downloadCount" placeholder="下载次数" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="查看次数">
                <a-input-number v-model:value="formData.viewCount" placeholder="查看次数" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="排序权重">
                <a-input-number v-model:value="formData.sortOrder" placeholder="排序权重" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 步骤操作按钮 -->
      <div class="step-actions">
        <a-button v-if="currentStep > 0" @click="prevStep">上一步</a-button>
        <a-button v-if="currentStep < 2" type="primary" @click="nextStep">下一步</a-button>
        <a-button v-if="currentStep === 2" type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isUpdate ? '更新' : '保存' }}
        </a-button>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, reactive, defineOptions } from 'vue';

  defineOptions({ name: 'BlogScriptsStepForm' });
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveOrUpdate } from '../BlogScripts.api';
    import { message } from 'ant-design-vue';
  import Vue3Emoji from 'vue3-emoji';
  import { CodeEditor } from '/@/components/CodeEditor';

  // Emits声明
  const emit = defineEmits(['register', 'success']);

  const currentStep = ref(0);
  const submitLoading = ref(false);
  const isUpdate = ref(false);
  const optionsName = {
    'Smileys & Emotion': '表情',
    'Food & Drink': '食物&饮料',
    'Animals & Nature': '动物&自然',
    'Travel & Places': '旅行&地点',
    'People & Body': '人物&身体',
    Objects: '物品',
    Symbols: '符号',
    Flags: '旗帜',
    Activities: '活动',
  };

  // 颜色预设
  const colorPresets = ref([
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', // 蓝紫
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)', // 粉红
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)', // 绿青
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)', // 粉黄
    'linear-gradient(135deg, #30cfd0 0%, #330867 100%)', // 青蓝
    'linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%)', // 浅蓝
    'linear-gradient(135deg, #f7971e 0%, #ffd200 100%)', // 橙黄
    'linear-gradient(135deg, #f857a6 0%, #ff5858 100%)', // 紫红
    'linear-gradient(135deg, #00c6fb 0%, #005bea 100%)', // 靛蓝
    'linear-gradient(135deg, #fceabb 0%, #f8b500 100%)', // 米黄
    'linear-gradient(135deg, #76b852 0%, #8dc26f 100%)', // 草绿
    'linear-gradient(135deg, #e0c3fc 0%, #8ec5fc 100%)', // 紫蓝淡
    'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)', // 灰蓝
    'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)', // 橙粉
    'linear-gradient(135deg, #c471f5 0%, #fa71cd 100%)', // 紫粉
    'linear-gradient(135deg, #48c6ef 0%, #6f86d6 100%)', // 蓝灰
  ]);

  // 表单数据
  const formData = reactive({
    id: '',
    name: '',
    fileName: '',
    fileSize: 0,
    description: '',
    content: '',
    icon: '',
    color: '',
    status: 'draft',
    systems: '',
    features: '',
    techStack: '',
    downloadCount: 0,
    viewCount: 0,
    sortOrder: 0,
    createdBy: '',
    createdTime: '',
    updatedBy: '',
    updatedTime: '',
    deleted: 0,
  });

  const icon = ref('');

  // 用于输入的临时变量
  const systemsInput = ref('');
  const featuresInput = ref('');
  const techStackInput = ref('');

  // 表单配置
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // 重置步骤到第一步
    currentStep.value = 0;

    // 重置表单
    Object.keys(formData).forEach((key) => {
      if (key === 'fileSize' || key === 'downloadCount' || key === 'viewCount' || key === 'sortOrder' || key === 'deleted') {
        formData[key] = 0;
      } else {
        formData[key] = '';
      }
    });
    formData.status = 'draft';

    // 重置输入变量
    systemsInput.value = '';
    featuresInput.value = '';
    techStackInput.value = '';
    icon.value = '';

    setModalProps({ confirmLoading: false, showCancelBtn: false, showOkBtn: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      // 表单赋值
      Object.keys(data.record).forEach((key) => {
        if (formData.hasOwnProperty(key)) {
          formData[key] = data.record[key];
        }
      });
      icon.value = data.record.icon || '';

      // 处理JSON数组字段的回显
      if (typeof formData.systems === 'string') {
        try {
          const systemsArray = JSON.parse(formData.systems);
          systemsInput.value = Array.isArray(systemsArray) ? systemsArray.join(',') : formData.systems;
        } catch (e) {
          systemsInput.value = formData.systems;
        }
      }

      if (typeof formData.features === 'string') {
        try {
          const featuresArray = JSON.parse(formData.features);
          featuresInput.value = Array.isArray(featuresArray) ? featuresArray.join(',') : formData.features;
        } catch (e) {
          featuresInput.value = formData.features;
        }
      }

      if (typeof formData.techStack === 'string') {
        try {
          const techStackArray = JSON.parse(formData.techStack);
          techStackInput.value = Array.isArray(techStackArray) ? techStackArray.join(',') : formData.techStack;
        } catch (e) {
          techStackInput.value = formData.techStack;
        }
      }
    }
  });

  // 设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增脚本' : '编辑脚本'));

  // 下一步
  const nextStep = () => {
    if (currentStep.value === 0) {
      if (!formData.name.trim()) {
        message.error('请输入脚本名称');
        return;
      }
      if (!formData.fileName.trim()) {
        message.error('请输入文件名');
        return;
      }
      if (!formData.description.trim()) {
        message.error('请输入脚本描述');
        return;
      }
    } else if (currentStep.value === 1) {
      if (!formData.content.trim()) {
        message.error('请输入脚本代码内容');
        return;
      }
    }
    currentStep.value++;
  };

  // 上一步
  const prevStep = () => {
    currentStep.value--;
  };

  // 选择emoji
  const selectEmoji = (val: any) => {
    console.log('选中的emoji', val);
    icon.value = typeof val === 'string' ? val : val.emoji;
  };

  // 表单提交事件
  async function handleSubmit() {
    try {
      // 验证必填字段
      if (!formData.name.trim()) {
        message.error('请输入脚本名称');
        return;
      }
      if (!formData.fileName.trim()) {
        message.error('请输入文件名');
        return;
      }
      if (!formData.description.trim()) {
        message.error('请输入脚本描述');
        return;
      }
      if (!formData.content.trim()) {
        message.error('请输入脚本代码内容');
        return;
      }

      formData.icon = icon.value;
      setModalProps({ confirmLoading: true });
      submitLoading.value = true;

      // 处理JSON数组字段
      if (systemsInput.value && typeof systemsInput.value === 'string') {
        const systemsArray = systemsInput.value
          .split(',')
          .map((item) => item.trim())
          .filter((item) => item);
        formData.systems = JSON.stringify(systemsArray);
      }

      if (featuresInput.value && typeof featuresInput.value === 'string') {
        const featuresArray = featuresInput.value
          .split(',')
          .map((item) => item.trim())
          .filter((item) => item);
        formData.features = JSON.stringify(featuresArray);
      }

      if (techStackInput.value && typeof techStackInput.value === 'string') {
        const techStackArray = techStackInput.value
          .split(',')
          .map((item) => item.trim())
          .filter((item) => item);
        formData.techStack = JSON.stringify(techStackArray);
      }

      // 提交表单
      await saveOrUpdate(formData, isUpdate.value);

      // 关闭弹窗
      closeModal();
      // 刷新列表
      emit('success');
      message.success(isUpdate.value ? '更新成功' : '保存成功');
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setModalProps({ confirmLoading: false });
      submitLoading.value = false;
    }
  }
</script>

<style lang="less" scoped>
  .step-form-container {
    padding: 12px 0 0 0;
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    min-height: 420px;
    max-width: 700px;
    margin: 0 auto;
    @media (max-width: 600px) {
      padding: 4px 0 0 0;
      min-height: 320px;
      border-radius: 0;
      max-width: 100vw;
    }
  }
  .step-steps {
    margin-bottom: 18px;
    background: transparent;
    border-radius: 0;
    padding: 0;
    box-shadow: none;
    :deep(.ant-steps-item-process .ant-steps-item-icon) {
      background: #3b82f6;
      border-color: #3b82f6;
      box-shadow: none;
    }
    :deep(.ant-steps-item-process .ant-steps-item-title) {
      color: #3b82f6;
      font-weight: 500;
      letter-spacing: 0.5px;
    }
    :deep(.ant-steps-item-title) {
      font-size: 15px;
      color: #888;
      font-weight: 400;
    }
    :deep(.ant-steps-item-description) {
      color: #b0b0b0;
      font-size: 12px;
    }
  }
  .step-content {
    min-height: 320px;
    padding: 0;
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    margin-bottom: 0;
    @media (max-width: 600px) {
      padding: 0;
      min-height: 180px;
    }
    a-form {
      padding: 0 16px;
      @media (max-width: 600px) {
        padding: 0 2px;
      }
    }
  }
  .step-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: #222;
    border: none;
    padding-bottom: 0;
    letter-spacing: 0.5px;
    text-align: left;
    padding-left: 16px;
    @media (max-width: 600px) {
      padding-left: 4px;
    }
  }
  .step-actions {
    text-align: center;
    margin-top: 18px;
    padding: 0 16px 16px 16px;
    border: none;
    background: transparent;
    border-radius: 0;
    .ant-btn {
      margin: 0 6px;
      min-width: 90px;
      font-size: 14px;
      border-radius: 18px;
      height: 34px;
      box-shadow: none;
      border: none;
      font-weight: 500;
      background: #f3f4f6;
      color: #222;
      transition: all 0.18s;
      &:hover {
        background: #e0e7ef;
        color: #2563eb;
      }
      &:active {
        background: #dbeafe;
        color: #2563eb;
      }
    }
    .ant-btn-primary {
      background: linear-gradient(90deg, #3b82f6 60%, #2563eb 100%);
      color: #fff;
      font-weight: 600;
      box-shadow: none;
      border: none;
      &:hover,
      &:active {
        background: linear-gradient(90deg, #2563eb 60%, #3b82f6 100%);
        color: #fff;
      }
    }
  }
  .form-tip {
    font-size: 12px;
    color: #b0b0b0;
    margin-top: 2px;
  }
  :deep(.ant-form-item) {
    margin-bottom: 18px;
  }
  :deep(.ant-input),
  :deep(.ant-input-number),
  :deep(.ant-textarea) {
    border-radius: 8px;
    font-size: 15px;
    min-height: 32px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    box-shadow: none;
    transition: border 0.18s;
    &:focus,
    &:hover {
      border-color: #3b82f6;
      background: #fff;
    }
  }
  :deep(.ant-input-number) {
    width: 100%;
  }
  :deep(.ant-radio-group) {
    font-size: 15px;
    .ant-radio-inner {
      border-radius: 50%;
      border-color: #d1d5db;
    }
    .ant-radio-checked .ant-radio-inner {
      border-color: #3b82f6;
      background: #3b82f6;
    }
  }
  :deep(.ant-form-item-label > label) {
    font-weight: 400;
    color: #888;
    letter-spacing: 0.2px;
    font-size: 14px;
  }

  .emoji-form-row {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .emoji-input {
    flex: 2;
    min-width: 200px;
    max-width: 320px;
  }
  .emoji-trigger {
    cursor: pointer;
  }
  .clear-emoji {
    color: #999;
    margin-left: 4px;
  }
  .emoji-preview {
    font-size: 18px;
  }

  .color-selector {
    .color-presets {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;
      flex-wrap: wrap;
      .color-option {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        cursor: pointer;
        border: 3px solid #fff; // 白色内边框，保证渐变色下清晰
        box-shadow: 0 0 0 1.5px #d1d5db; // 外发光，提升对比度
        transition: all 0.2s;
        position: relative;
        background-clip: padding-box;
        &:hover {
          box-shadow:
            0 0 0 3px #2563eb,
            0 0 0 1.5px #d1d5db;
          border-color: #2563eb;
        }
        &.active {
          border-color: #2563eb;
          box-shadow:
            0 0 0 3px #2563eb,
            0 0 0 1.5px #d1d5db;
          &::after {
            content: '✓';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
            font-size: 14px;
            font-weight: bold;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
            pointer-events: none;
          }
        }
      }
    }
    .selected-color {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      border-radius: 8px;
      color: white;
      font-size: 12px;
      min-height: 40px;
      position: relative;
      overflow: hidden;
      .color-value {
        font-weight: 500;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .clear-color {
        color: rgba(255, 255, 255, 0.9);
        background: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        padding: 2px 6px;
        &:hover {
          color: white;
          background: rgba(0, 0, 0, 0.3);
        }
      }
    }
  }

  .emoji-picker-inline {
    min-height: 320px;
    max-height: 420px;
    margin-top: 8px;
    border-radius: 8px;
    background: #f8fafc;
    overflow-y: auto;
    padding: 8px 0;
    :deep(.vue3-emoji) {
      border: none;
      background: transparent;
    }
  }

  :deep([class*='emojiItem']) {
    width: auto !important;
  }

  .emoji-input {
    width: 220px;
    min-width: 0;
    max-width: none;
    flex: none;
  }

  :deep(.CodeMirror) {
    border-radius: 8px;
    font-size: 15px;
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    min-height: 400px;
  }

  :deep(.CodeMirror-gutters) {
    display: block !important;
    background: #f8fafc !important;
    border-right: none !important;
    color: #b0b0b0 !important;
    min-width: 36px;
  }
  :deep(.CodeMirror-linenumbers) {
    color: #b0b0b0 !important;
    font-size: 13px !important;
  }
  :deep(.CodeMirror-linenumber) {
    color: #94a3b8 !important;
    font-family: monospace;
    padding-right: 8px;
  }
</style> 